<?php
class SeoComponent extends Object
{
	var $meta = null;
	
	function configureMeta($url)
	{
		$model = ClassRegistry::init('Meta');//the table name
		$url = $this->standardizeURL($url);
		$this->meta = $model->query("SELECT * FROM metas AS Meta WHERE Meta.url = '$url'");
		if(empty($this->meta))
		{
			$rootmeta = $model->query("SELECT * FROM metas AS Meta WHERE Meta.url = '/'");
			if(!empty($rootmeta))
			{
				$this->meta = $rootmeta;
			}
		}
	}
	
	function checkURLExists($url="")
	{		
		$model = ClassRegistry::init('Meta');//the table name
		$url = $this->standardizeURL($url);
		$r=$model->query("SELECT * FROM metas AS Meta WHERE Meta.url = '$url'");
		$rr =!empty($r);
		return $rr;
	}
	
	function  standardizeURL($url="")
	{
		if($url && $url!='/')
		{
			for($i =0; $i<26; $i++)
			{ 			
				$url = str_replace("//","/",$url);
			}
			if(substr($url,0,1)=='/')
			{
				$url = substr($url,1,strlen($url));
			}
			if('/'==substr($url, strlen($url)-1,1))
			{
				$url = substr($url,0,strlen($url)-1);
			}
		}
		return $url;
	}
	
	function getStr($metaName = null, $arr = null)
	{
		if(is_null($metaName))
			return '';
		$returnStr = '';
		switch($metaName)
		{
			case 'page_title':
				$returnStr = __(DEFAULT_PAGE_TITLE, true);
				break;
			case 'meta_title':
				$returnStr = __(DEFAULT_META_TITLE, true);
				break;
			case 'meta_keywords':
				$returnStr = __(DEFAULT_KEYWORD, true);
				break;
			case 'meta_description':
				$returnStr = __(DEFAULT_DESCRIPTION, true);
		}
		$returnStr = count($this->meta)>0 && $this->meta[0]['Meta'][$metaName] ? $this->meta[0]['Meta'][$metaName] : $returnStr;
		if(!is_null($arr))
			if(!is_array($arr))
				$returnStr = $arr;
			else
			{
				//~ $returnStr = $this->_replaceElement($arr, $returnStr);
				$returnStr = $this->_tpl_replace($arr, $returnStr);
			}
				
		return $returnStr;
	}
	
	function _replaceElement($arr, $str)
	{
		foreach($arr as $key=>$param)
			if(preg_match("{.}", $str))
			{
				$str = preg_replace("/{.[^}]+}/", $param, $str, 1);
				//~ $str = preg_replace('/<\{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}>/i', $arr[$key], $str, 1);
			}
		return $str;
	}
	  
	private function _tpl_replace($arr, $repContent)
	{   
		$i=0;
		foreach($arr as $key=>$value)
		{
			$keys = array_keys($arr);
			// debug($arr);
			// debug($keys);
			if(stristr($repContent,"<{".$keys[$i]."}>")) 
			{
				$repContent=str_replace("<{".$keys[$i]."}>", $arr[$key],$repContent);    
			}
			$i++;
		} 
		return $repContent;
	}  
}

?>
